<template>
	<view class="collect-or-wrong page-padding">
		<!-- 统计总数 -->
		<ring-chart :count="total" :flag="flag" />
		<!-- 题目列表 -->
		<view class="list">
			<view class="item" v-for="(item,index) in list" :key="item.value" @click="questionClick(index)">
				<view class="left single-line-overflow">{{index + 1}}.{{item.label}}</view>
				<view class="right">></view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onPullDownRefresh,
		onReachBottom
	} from '@dcloudio/uni-app'
	import {
		onMounted,
		ref
	} from 'vue'
	import {
		getCollectSimpleInfo,
		getMistakeSimpleInfo,
		getQuestionDetailById
	} from '@/service/modules/personal';
	import {
		useTestQuestionStore
	} from '@/store';

	// 获取仓库数据
	const testQuestionStore = useTestQuestionStore()

	// 0代表收藏页面 1代表错题页面
	const flag = ref('0')
	// 当前页数
	const pageNum = ref(1)
	// 列表数据
	const list = ref([])
	// 总数
	const total = ref(0)

	onLoad((options) => {
		// 动态修改标题
		uni.setNavigationBarTitle({
			title: options.flag === '0' ? '我的收藏' : '错题集'
		})
		flag.value = options.flag
	})
	// 下拉刷新
	onPullDownRefresh(async () => {
		pageNum.value = 1
		await getList()
		// 请求成功关闭下拉状态
		uni.stopPullDownRefresh()
		console.log('关闭下拉状态');
	})
	// 上拉触底
	onReachBottom(() => {
		pageNum.value = pageNum.value + 1
		getList(true)
	})

	onMounted(() => {
		getList()
	})

	const questionClick = (index) => {
		// 更新当前题目解析索引
		testQuestionStore.currentQuestionIndex = index
		// 跳转答题页面
		uni.navigateTo({
			url: '/pages/test-question/test-question?status=hide&title=' + encodeURIComponent(flag.value === '0' ?
				'我的收藏' : '错题集')
		})
	}

	const getList = async (isPush) => {
		// 判断发收藏集还是错题集的请求
		const getData = flag.value === '0' ? getCollectSimpleInfo : getMistakeSimpleInfo
		const res = await getData(pageNum.value)
		console.log('列表', res);
		// 触底要追加数据
		if (isPush) {
			list.value.push(...res.data.list)
			if (list.value.length >= total.value) {
				list.value = list.value.slice(0, total.value)
				uni.showToast({
					icon: "error",
					title: "已经到底了哦~"
				})
			}
		} else {
			// 这是初次加载或者下拉刷新的赋值情况
			list.value = res.data.list
			total.value = res.data.total
		}
		// 根据题目id获取详情列表
		const promiseList = []
		list.value.forEach(item => {
			promiseList.push(getQuestionDetailById(item.value))
		})
		const resList = await Promise.all(promiseList)
		const detailList = resList.map(item => item.data)
		// 更新当前题库内容
		testQuestionStore.questionList = detailList
		testQuestionStore.isReviewing = true
	}
</script>

<style lang="scss">
	page {
		background-color: $bg-color;
	}

	.list {
		width: 100%;

		.item {
			display: flex;
			border: 2rpx solid $second-primary-color;
			margin-bottom: 20rpx;
			padding: 20rpx 10rpx;
			border-radius: 20rpx;
			color: $text-color;
			font-size: 26rpx;

			.left {
				flex: 1;
			}

			.right {
				width: 80rpx;
				text-align: right;
			}
		}
	}
</style>